Return the summation of the number smaller than n


Posted by Christy on 2022-04-19

Description: Write a function named findSmallerTotal that accepts an array and a number n, returns the summation of the number smaller than n.

function findSmallerTotal(arr, n) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      sum += arr[i];
    }
  }
  return sum;
}

console.log(findSmallerTotal([1, 2, 3], 3)); // 3
console.log(findSmallerTotal([1, 2, 3], 1)); // 0
console.log(findSmallerTotal([3, 2, 5, 8, 7], 999)); // 25
console.log(findSmallerTotal([3, 2, 5, 8, 7], 0)); // 0

The other answers:

function findSmallerTotal(arr, n) {
  let i = 0;
  let sum = 0;
  do {
    if (arr[i] < n) {
      sum += arr[i];
    }
    i++;
  } while (i < arr.length);
  return sum;
}
function findSmallerTotal(arr, n) {
  let i = 0;
  let sum = 0;
  while (i < arr.length) {
    if (arr[i] < n) {
      sum += arr[i];
    }
    i++;
  }
  return sum;
}









Related Posts

第五天:爬蟲【三】

第五天:爬蟲【三】

 滲透測試重新打底(3.3)--論Web入侵之任意檔案上傳漏洞

滲透測試重新打底(3.3)--論Web入侵之任意檔案上傳漏洞

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段二:專題研討+協作練習專案)

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段二:專題研討+協作練習專案)


Comments